﻿#include "csvworker.h"
#include <QDateTime>
#include <QTextStream>
#include <QTextCodec>
CsvWorker::CsvWorker(QObject *parent) : QObject(parent)
{

}
void CsvWorker::slotWriteIn(CsvData m_csData)
{
    // 1.创建文件  根据时间进行命名
    //2.文件名采用系统时间戳生成唯一的文件
    QString username;
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy_MM_dd");
    QString csvDir = tr("/%1_DTUConfigInfo_export_%2.csv").arg(username).arg(current_date);
    CreateCsvFile("data",csvDir);
    // 2.打开文件
    QFile data(csvFile);
    // 3.进行写入
    if (data.open(QFile::ReadWrite | QFile::Text | QIODevice::Append))        // 打开文件
    {
        QTextStream out(&data);    // 输入流
        //        out << m_csData.csStarTime <<","<<  m_csData.csStopTime <<","<< m_csData.csUser
        //            <<","<< m_csData.csSum <<","<< m_csData.csGood <<","<< m_csData.csBad
        //           <<","<< m_csData.csGoodRation <<","<< m_csData.csBadRation <<","<< m_csData.csCamerBad1
        //          <<","<< m_csData.csCamerBad2 <<","<< m_csData.csCamerBad3 <<","<< m_csData.csCamerBad4
        //         << "\n";
        out << m_csData.csStarTime <<","<<  m_csData.csIndex <<","<< m_csData.csIn_Round
            <<","<< m_csData.csOut_Round <<","<< m_csData.csIn_Len <<","<< m_csData.csOut_Len
           <<","<< m_csData.csLen << ","<< m_csData.csNGorOK << "\n";
    }
    // 4.关闭文件
    data.close();
}

void CsvWorker::slotReadOut()
{

}

void CsvWorker::CreateCsvFile(QString filePath,QString fileName)
{
    QDir tempDir;
    //临时保存程序当前路径
    QString currentDir = tempDir.currentPath();
    //如果filePath路径不存在，创建它
    if(!tempDir.exists(filePath))
    {
        tempDir.mkpath(filePath);
    }
    QFile tempFile(fileName);
    //将程序的执行路径设置到filePath下
    tempDir.setCurrent(filePath);
    csvFile = tempDir.currentPath()+fileName;
    //检查filePath路径下是否存在文件fileName,如果停止操作。
    if(tempFile.exists(fileName))
    {
        return;
    }
    //此时，路径下没有fileName文件，使用下面代码在当前路径下创建文件
    tempFile.setFileName(csvFile);
    //    QString strData = QString::fromLocal8Bit("检测时间,停止时间,操作者,进料总数,良品数,"
    //                                             "不良数,合格率,不合格率,相机1废品数,相机2废品数,相机3废品数,相机4废品数,");


    QString strData = QString::fromLocal8Bit("检测时间,料号,内圆度,外圆度,内直径,外直径,长度");

    if(tempFile.open( QIODevice::ReadWrite | QIODevice::Text ))
    {
        QTextStream out(&tempFile);    // 设置标题
        out << strData  << "\n";
    }
    tempFile.close();
    //将程序当前路径设置为原来的路径
    tempDir.setCurrent(currentDir);
}
